<%@page import="java.sql.*"%>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
	.kuang{width:1200px;margin:auto;}
	h1{color:red; text-align:center;}
	.nav{ margin-bottom:10px;}
	a{ text-decoration:none;color:gray;}
	a:hover{ color:red;}
	.context{ display:flex; border:3px solid red;}
	.column{ flex-grow:1; border:1px solid gray; margin:10px;padding:10px}
	p{margin:0;}
	h2{ text-align:center;}
</style>
<title>分页显示成语</title>
</head>
<body>
<h1>中国成语大全</h1>
<h2>作者:张艳宾</h2>
<div class='kuang'>
<div class='nav'>
<% 
String url="jdbc:mysql://localhost:3306/db?serverTimezone=PRC";
//(1)加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//(2)创建连接
Connection cn = DriverManager.getConnection(url,"root","12qwas");
//(3)创建sql插入语句并设定参数的值
PreparedStatement ps = cn.prepareStatement("select count(1) from chengyu");
ResultSet rs = ps.executeQuery();
rs.next();
int total=rs.getInt(1);//成语的总条数
int lanNumber=6;//分栏的个数
int chengyuCountPerLan=23;//每个分栏成语的个数
int pageSize=lanNumber*chengyuCountPerLan;//一个页面成语的个数
int totalPages=total/pageSize+(total%pageSize==0?0:1);//最大页面数
//获取用户要显示的当前页码
String page1=request.getParameter("page");//接收的参数都是字符串类型的数据
if(page1==null)page1="1";//值为null，默认显示第一页
int currentPage= Integer.parseInt(page1);//字符串转为int型
if(currentPage<1)currentPage=1;//页面小于1，默认为1
else if(currentPage>totalPages)currentPage=totalPages;
	//out.print(currentPage);//位于合理范围内的一个页面值
	int n=15;//当前显示的页面前后数字导航超链接的个数
	int begin=currentPage-n;
	int over=currentPage+n;
	if(begin<1){
		begin=1;
		over=2*n+1;
	if(over>totalPages)over=totalPages;
	}else if(over>totalPages){
		over=totalPages;
		begin=totalPages-2*n;
		if(begin<1)begin=1;
	}
	for(int i=begin; i<=over; ++i){
		if(i==currentPage)out.print("\t\t<b>"+i+"</b>");
		else out.println("\t\t<a href='?page="+i+"'>"+i+"</a>");//"+i+"
		}
	out.println("\t</div>");
	out.println("\t<div class='context'>");
	ps = cn.prepareStatement("select cy from chengyu limit ?,?");
	ps.setInt(1, (currentPage-1)*pageSize);
	ps.setInt(2,pageSize);
	rs = ps.executeQuery();
	for(int i=0;i<lanNumber;++i){
		out.println("\t\t<div class='column'>");
	
	for(int j=0;j<chengyuCountPerLan;++j){
		if(rs.next()) out.println("\t\t\t<p>"+rs.getString("cy")+"</p>");
		else out.println("\t\t<p>    </p>");
	}
	out.println("\t\t</div>");
	}
	out.println("\t</div>");
	
%>
</div>
</div>
</body>
</html>